//token验证
var jwt = require('jsonwebtoken')
var secret = 'thisiszhangliisprivatekeypleasedonotpassiton' //私钥

var checktoken = function(req,res,next){
    console.log('接口拦截的自定义中间件函数',req.headers.token);
    
    let {token} = req.headers
    jwt.verify(token,secret,(err,decoded)=>{
        console.log(err,decoded);
       if(err){ // 合法性
           res.send({
               code:110,
               msg:'非法token，请登录'
           })
           return 
       } 
       let {time,limit} = decoded
       let now = Date.now()
       if(now-time>=limit){// 有效性
           res.send({
               code:111,
               msg:'token已过期，请重新登录'
           })
           return
       }
    })
    next()  // 验证通过
}

module.exports = {
    checktoken
}